<template>
  <div class="layer-tool">
    <el-tooltip content="选择" placement="top">
      <SvgIcon class="tool" icon-class="ic_选择" @click="onclick('select')" />
    </el-tooltip>
    <el-tooltip content="框选" placement="top">
      <SvgIcon class="tool" icon-class="ic_框选" @click="onclick('box-select')" />
    </el-tooltip>

    <div class="split-line"></div>

    <el-tooltip content="平移" placement="top">
      <SvgIcon class="tool" icon-class="ic_平移" @click="onclick('translation')" />
    </el-tooltip>
    <el-tooltip content="旋转" placement="top">
      <SvgIcon class="tool" icon-class="ic_旋转" @click="onclick('rotate')" />
    </el-tooltip>
    <el-tooltip content="缩放" placement="top">
      <SvgIcon class="tool" icon-class="ic_缩放" @click="onclick('scale')" />
    </el-tooltip>
    <el-tooltip content="上下位移" placement="top">
      <SvgIcon class="tool" icon-class="ic_上下位移" @click="onclick('displacement')" />
    </el-tooltip>

    <div class="split-line"></div>
    <el-tooltip v-if="isGltf" content="复制" placement="top">
      <SvgIcon class="tool" icon-class="ic_复制" @click="onclick('copy')" />
    </el-tooltip>
    <el-tooltip v-if="isGltf" content="吸管" placement="top">
      <SvgIcon class="tool" icon-class="ic_吸管" @click="onclick('staw')" />
    </el-tooltip>
    <el-tooltip v-if="isLayer" content="删除" placement="top">
      <SvgIcon class="tool" icon-class="ic_删除" @click="onclick('delete')" />
    </el-tooltip>
  </div>
</template>

<script setup lang="ts">
import { getLayerMap } from '@/service';
import { deleteLayer } from '@/service/layer';
import { useSceneStore } from '@/store/scene';
import { randomString } from '@/utils';
import { messageUtil } from '@jl/element-plus/utils';
import { cloneDeep } from 'lodash';
import { deleteTreeNode } from '@/utils';
import { initTridentEvent } from '@/service/layer';

defineOptions({
  name: 'LayerTool',
});

const sceneStore = useSceneStore();
const isLayer = computed(() => sceneStore.selLayer?.type !== 'folder');
const isGltfModel = computed(() => sceneStore.selLayer?.type === 'gltfmodel'); // gltf，模型特效
const isGltf = computed(
  () =>
    sceneStore.selLayer?.type === 'gltfmodel' &&
    sceneStore.selLayer?.actualType !== 'gltfmodeleffect'
);

const onclick = (type: string) => {
  if (['select', 'box-select', 'translation', 'rotate', 'scale', 'displacement'].includes(type)) {
    messageUtil.info('该功能暂未开放');
    return;
  }
  if (type === 'copy') {
    copyLayer();
  }
  if (type === 'delete') {
    removeLayer();
  }
  if (type === 'staw') {
  }
};

// 复制图层
const copyLayer = () => {
  const { cimInstance } = window;
  if (!sceneStore.selectedLayerNode || sceneStore.selLayer?.type === 'folder') {
    messageUtil.info('未选择图层');
    return;
  }
  const copyLayer = cloneDeep(sceneStore.selLayer);
  const config = cimInstance.api.getCurrentLayerConfig(sceneStore.selLayer.layerName);

  const copyConfig = cloneDeep(config);
  // gltf,模型特效 复制
  if (['gltfmodel'].includes(copyLayer.type)) {
    copyLayer.code = Math.random().toString().split('.')[1];
    if (copyLayer?.actualType === 'gltfmodeleffect') {
      copyLayer.layerName = '模型特效' + copyLayer.code;
      copyConfig.positions[0][0] += 0.005;
    } else {
      copyLayer.layerName = copyLayer.name + '_gltf_' + Math.random().toString().split('.')[1];
    }
    if (!copyConfig.translation) {
      copyConfig.translation = [0, 0, 0];
    }

    copyConfig.name = copyLayer.layerName;
    const result = cimInstance.api.getGraphicInfo(config.name, null, {
      boundingSphere: true,
    });
    if (result) {
      const len = 3 * result.boundingSphere.radius;
      const poi = cimInstance.api.getTransformedPosition({
        position: copyConfig.positions[0],
        translation: copyConfig.translation,
        rotation: copyConfig.rotation,
      });
      const position = cimInstance.api.getTransformedPosition({
        position: poi,
        translation: [len, 0, 0],
      });
      copyConfig.positions[0] = position;
      copyConfig.translation = [0, 0, 0];
    }
    const layerMap = getLayerMap();
    layerMap.set(copyLayer.code, copyLayer.code);

    cimInstance.api.addLayerByType(copyConfig);
    copyLayerTree(copyLayer);
  }
  // 离子特效。暂时无法实现：需引擎提供
  if (['entity'].includes(copyLayer.type)) {
  }
};

const copyLayerTree = (currentLayer: any) => {
  const param = {
    ...currentLayer,
    id: '',
    fe_id: randomString(),
    fe_checked: true,
    fe_indeterminate: false,
    fe_parentId: '',
  };
  param.id = param.fe_id;
  const parent = sceneStore.selectedLayerNode.parent || { level: 0, data: [] };
  const currData = sceneStore.selectedLayerNode.data;
  let updatedNodeData;
  if (parent.level === 0) {
    updatedNodeData = parent.data;
    const index = updatedNodeData.findIndex((item: any) => item.fe_id === currData.fe_id);
    updatedNodeData.splice(index, 0, param);
  } else {
    updatedNodeData = parent.data;
    param.fe_parentId = updatedNodeData.fe_id;
    const index = updatedNodeData.children.findIndex((item: any) => item.fe_id === currData.fe_id);
    updatedNodeData.children.splice(index, 0, param);
  }
  // 默认选中逻辑
  const layer = sceneStore.selLayer;
  const { cimInstance } = window;
  // 取消之前图层三叉轴监听
  cimInstance.api.changeOrbitControlMode('');
  cimInstance.api.deleteOrbitControl(layer.layerName);

  sceneStore.selLayer = param;
  initTridentEvent(param);
  sceneStore.layerList.unshift(param);
  sceneStore.selectedLayerNode = null;
};

const removeLayer = () => {
  if (!sceneStore.selectedLayerNode || sceneStore.selLayer?.type === 'folder') {
    messageUtil.info('未选择图层');
    return;
  }
  const layer = sceneStore.selLayer;
  deleteTreeNode(sceneStore.layerTree, layer.fe_id, {
    id: 'fe_id',
  });
  deleteLayer(layer);
};
</script>

<style lang="less" scoped>
.layer-tool {
  position: absolute;
  top: 80px;
  left: 50%;
  transform: translateX(-50%);
  height: 42px;
  background: #1d1e1f;
  border-radius: 4px;
  opacity: 0.8;
  font-size: 24px;
  display: flex;
  align-items: center;
  z-index: 1;
  padding-right: 20px;
  pointer-events: initial;

  .split-line {
    width: 1px;
    height: 16px;
    background: #585858;
    border-radius: 1px;
    margin-left: 20px;
  }

  .tool {
    margin-left: 20px;
    cursor: pointer;
  }
}
</style>
